const router = require("../router");
const jwt = require("jsonwebtoken");

const { mongoose } = require("../mongodb");

const Schema = mongoose.Schema;

const expireTime = 60 * 60;

router.post("/login", async function (req, res) {
  const { uname, upwd } = req.body;

  const registerSchema = new Schema({
    uname: String,
    upwd: String,
  });

  const Register = mongoose.model("Register", registerSchema);

  const register = new Register({
    uname,
    upwd,
  });

  const token = jwt.sign({ uname, upwd }, "auth", { expiresIn: expireTime });

  register.save().then(
    (result) => {
      console.log("成功的回调", result);

      res.json({
        code: "0",
        data: {
          token,
        },
        msg: "成功",
        success: true,
      });
    },
    (err) => {
      console.log("失败的回调", err);

      res.json({
        code: "-1",
        data: {
          err: err,
        },
        msg: "失败",
        success: false,
      });
    }
  );
});

module.exports = router;
